package com.qxbb.report.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qxbb.report.Enum.*;
import com.qxbb.report.bo.*;
import com.qxbb.report.dao.*;
import com.qxbb.report.dto.*;
import com.qxbb.report.pojo.*;
import com.qxbb.report.service.ChainStoreService;
import com.qxbb.report.service.ProductSalesService;
import com.qxbb.report.utils.StringUtils;
import com.qxbb.report.utils.ZipImgUtils;
import com.qxbb.report.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @author: pebble
 * @data 2023/10/9 13:39
 */
@Service
public class ProductSalesServiceImpl extends ServiceImpl<ChainSalesOrderProductMapper, ChainSalesOrderProduct> implements ProductSalesService {

    @Autowired
    private ColorMapper colorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ChainSalesOrderProductMapper orderProductMapper;
    @Autowired
    private ChainUserInforMapper chainUserInforMapper;
    @Autowired
    private ChainStoreGroupElementmMapper chainStoreGroupElementmMapper;
    @Autowired
    private ChainStoreMapper chainStoreMapper;
    @Autowired
    private ChainInOutStockMapper chainInOutStockMapper;
    @Autowired
    private ChainStoreService chainStoreService;
    @Autowired
    private ZipImgUtils zipImgUtils = new ZipImgUtils();


    private SalesBO getSalesBo(CommonSalesBO commonSalesBO) {
        SalesBO salesBO = new SalesBO();
        List<Integer> chainStrore = new ArrayList<>();
        if (StringUtils.isNotNull(commonSalesBO.getChainStore())) {
            chainStrore.add(commonSalesBO.getChainStore());
        }
        //总部用户
        if (commonSalesBO.getUserType() == LoginUserType.HEADQUARTERS.getNumber() && StringUtils.isNull(commonSalesBO.getChainStore())) {
            salesBO.setQuarter(null);
            salesBO.setHandledBy(null);
            salesBO.setYear(commonSalesBO.getYearId());
            salesBO.setChainStore(chainStoreMapper.selectAllNonDeleted());
            salesBO.setStartTime(commonSalesBO.getStartTime());
            salesBO.setEndTime(commonSalesBO.getEndTime());
            // 连锁店用户
        } else if (commonSalesBO.getUserType() == LoginUserType.chain_store.getNumber() && StringUtils.isNull(commonSalesBO.getChainStore())) {
            ChainUserInfor chainUserInfor = chainUserInforMapper.selectByUserId(commonSalesBO.getUserId());
            // 连锁店经营者下所有店铺
            List<Integer> chainUserStore = chainStoreGroupElementmMapper.selectAllChain(chainUserInfor.getUserId());
            if (StringUtils.isEmpty(chainUserStore)){
                chainUserStore.add(chainUserInfor.getChainId());
            }
            // 连锁店经营者
            if (chainUserInfor.getRoleType() == ChainRoleType.CHAIN_STORE_OPERATOR.getRoleType()) {
                // 直营连锁店
                // todo (原判断直营连锁店：位置5 ，共6处）
                salesBO.setYear(commonSalesBO.getYearId());
                salesBO.setQuarter(null);
                salesBO.setHandledBy(null);
                salesBO.setChainStore(chainUserStore);
                salesBO.setStartTime(commonSalesBO.getStartTime());
                salesBO.setEndTime(commonSalesBO.getEndTime());

            } else {  // 连锁店店长，店员 并且店铺为空
                chainStrore.add(chainUserInfor.getChainId());
                salesBO.setQuarter(null);
                salesBO.setHandledBy(null);
                salesBO.setYear(commonSalesBO.getYearId());
                salesBO.setChainStore(chainStrore);
                salesBO.setStartTime(commonSalesBO.getStartTime());
                salesBO.setEndTime(commonSalesBO.getEndTime());
            }
        } else { // 有店铺，有经受人情况
            salesBO.setQuarter(null);
            salesBO.setYear(commonSalesBO.getYearId());
            salesBO.setHandledBy(commonSalesBO.getHandledBy());
            salesBO.setChainStore(chainStrore);
            salesBO.setStartTime(commonSalesBO.getStartTime());
            salesBO.setEndTime(commonSalesBO.getEndTime());
        }
        return salesBO;
    }

    @Override
    public List<StatisticsYearVO> selectYear(ChainOrderSalerBO chainOrderSalerBO) {
        // 1.查询该店铺具体时间段内所有年度季节的销售记录
        List<StatisticsYearVO> list = new ArrayList<>();
        SalesBO salesBO = getSalesBo(CommonSalesBO.builder()
                .userType(chainOrderSalerBO.getUserType())
                .userId(chainOrderSalerBO.getUserId())
                .handledBy(chainOrderSalerBO.getHandledBy())
                .chainStore(chainOrderSalerBO.getChainStore())
                .startTime(chainOrderSalerBO.getStartTime())
                .endTime(chainOrderSalerBO.getEndTime())
                .build());
        List<ProductSalesVO> salesVOList = orderProductMapper.selectProductSales(salesBO);
        HashMap<Integer, StatisticsYearVO> statisticsYearMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (ProductSalesVO productSalesVO : salesVOList) {
                int yearId = productSalesVO.getYearId();
                StatisticsYearVO statisticsYearVOInMap = statisticsYearMap.get(yearId);
                if (statisticsYearVOInMap == null) {
                    statisticsYearVOInMap = new StatisticsYearVO();
                }
                statisticsYearVOInMap.setYear(colorMapper.selectYearMsg(yearId));
                statisticsYearVOInMap.setYearId(yearId);
                if (productSalesVO.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    statisticsYearVOInMap.setNetSalesAmount(statisticsYearVOInMap.getNetSalesAmount() + productSalesVO.getNetSalesAmount());
                    statisticsYearVOInMap.setNetSalesVolume(statisticsYearVOInMap.getNetSalesVolume() + productSalesVO.getNetSalesVolume());
                    statisticsYearVOInMap.setNetCost(statisticsYearVOInMap.getNetCost() + productSalesVO.getNetCost());
                    statisticsYearVOInMap.setProfit(statisticsYearVOInMap.getProfit() + productSalesVO.getNetSalesAmount() - productSalesVO.getNetCost());
                } else if (productSalesVO.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    statisticsYearVOInMap.setNetSalesAmount(statisticsYearVOInMap.getNetSalesAmount() - productSalesVO.getNetSalesAmount());
                    statisticsYearVOInMap.setNetSalesVolume(statisticsYearVOInMap.getNetSalesVolume() - productSalesVO.getNetSalesVolume());
                    statisticsYearVOInMap.setNetCost(statisticsYearVOInMap.getNetCost() - productSalesVO.getNetCost());
                    statisticsYearVOInMap.setProfit(statisticsYearVOInMap.getProfit() - (productSalesVO.getNetSalesAmount() - productSalesVO.getNetCost()));
                } else if (productSalesVO.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    statisticsYearVOInMap.setGiftQuantity(statisticsYearVOInMap.getGiftQuantity() + productSalesVO.getNetSalesVolume());
                    statisticsYearVOInMap.setProfit(statisticsYearVOInMap.getProfit() - productSalesVO.getNetCost());
                }
                statisticsYearMap.put(yearId, statisticsYearVOInMap);
            }
        }
        for (StatisticsYearVO statisticsYearVO : statisticsYearMap.values()) {
            list.add(statisticsYearVO);
        }
        return list.stream().sorted(Comparator.comparing(StatisticsYearVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }


    @Override
    public List<StatisticsQuanterVO> selectQuanter(QuanterChainSalerBO quanterChainSalerBO) {
        List<Integer> chainId = new ArrayList<>();
        chainId.add(quanterChainSalerBO.getChainStore());
        // 1.查询该店铺具体时间段内所有年度季节的销售记录
        List<StatisticsQuanterVO> list = new ArrayList<>();
        SalesBO salesBO = getSalesBo(CommonSalesBO.builder()
                .yearId(quanterChainSalerBO.getYear())
                .handledBy(quanterChainSalerBO.getHandledBy())
                .userType(quanterChainSalerBO.getUserType())
                .userId(quanterChainSalerBO.getUserId())
                .chainStore(quanterChainSalerBO.getChainStore())
                .startTime(quanterChainSalerBO.getStartTime())
                .endTime(quanterChainSalerBO.getEndTime())
                .build());
        List<ProductSalesVO> salesVOList = orderProductMapper.selectProductQuanter(salesBO);
        HashMap<Integer, StatisticsQuanterVO> statisticsQuanterMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (ProductSalesVO productSalesVO : salesVOList) {
                // 季度id
                int quanterId = productSalesVO.getQuarterId();
                // 查询季度信息
                StatisticsQuanterVO statisticsQuanterVoMap = statisticsQuanterMap.get(quanterId);
                if (statisticsQuanterVoMap == null) {
                    statisticsQuanterVoMap = new StatisticsQuanterVO();
                }
                // 添加季度信息
                statisticsQuanterVoMap.setQuanter(colorMapper.selectQuarterMsg(quanterId));
                statisticsQuanterVoMap.setQuanterId(quanterId);
                if (productSalesVO.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    statisticsQuanterVoMap.setNetSalesAmount(statisticsQuanterVoMap.getNetSalesAmount() + productSalesVO.getNetSalesAmount());
                    statisticsQuanterVoMap.setNetSalesVolume(statisticsQuanterVoMap.getNetSalesVolume() + productSalesVO.getNetSalesVolume());
                    statisticsQuanterVoMap.setNetCost((int) (statisticsQuanterVoMap.getNetCost() + productSalesVO.getNetCost()));
                    statisticsQuanterVoMap.setProfit(statisticsQuanterVoMap.getProfit() + productSalesVO.getNetSalesAmount() - productSalesVO.getNetCost());
                } else if (productSalesVO.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    statisticsQuanterVoMap.setNetSalesAmount(statisticsQuanterVoMap.getNetSalesAmount() - productSalesVO.getNetSalesAmount());
                    statisticsQuanterVoMap.setNetSalesVolume(statisticsQuanterVoMap.getNetSalesVolume() - productSalesVO.getNetSalesVolume());
                    statisticsQuanterVoMap.setNetCost((int) (statisticsQuanterVoMap.getNetCost() - productSalesVO.getNetCost()));
                    statisticsQuanterVoMap.setProfit(statisticsQuanterVoMap.getProfit() - (productSalesVO.getNetSalesAmount() - productSalesVO.getNetCost()));
                } else if (productSalesVO.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    statisticsQuanterVoMap.setGiftQuantity(statisticsQuanterVoMap.getGiftQuantity() + productSalesVO.getNetSalesVolume());
                    statisticsQuanterVoMap.setProfit(statisticsQuanterVoMap.getProfit() - productSalesVO.getNetCost());
                }
                statisticsQuanterMap.put(quanterId, statisticsQuanterVoMap);
            }
        }
        for (StatisticsQuanterVO statisticsQuanterVO : statisticsQuanterMap.values()) {
            list.add(statisticsQuanterVO);
        }
        return list.stream().sorted(Comparator.comparing(StatisticsQuanterVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<BrandVO> selectByBrand(BrandOrderSalerBO brandOrderSalerBO) {
        List<BrandVO> list = new ArrayList<>();
        List<Integer> chainIds = new ArrayList<>();
        List<Integer> chainId = new ArrayList<>();
        if (StringUtils.isNotNull(brandOrderSalerBO.getChainStore())) {
            chainId.add(brandOrderSalerBO.getChainStore());
        } else {
            chainIds = getSalesBo(CommonSalesBO.builder()
                    .yearId(brandOrderSalerBO.getYearId())
                    .quarterId(brandOrderSalerBO.getQuarterId())
                    .userType(brandOrderSalerBO.getUserType())
                    .userId(brandOrderSalerBO.getUserId())
                    .chainStore(brandOrderSalerBO.getChainStore())
                    .startTime(brandOrderSalerBO.getStartTime())
                    .endTime(brandOrderSalerBO.getEndTime())
                    .build()).getChainStore();
        }

        // 查询具体品牌
        List<BrandDTO> salesVOList = orderProductMapper.selectBrandDto(
                brandOrderSalerBO.getYearId(),
                brandOrderSalerBO.getQuarterId(),
                brandOrderSalerBO.getChainStore() == null ? chainIds : chainId,
                brandOrderSalerBO.getHandledBy(),
                brandOrderSalerBO.getStartTime(),
                brandOrderSalerBO.getEndTime()
        );
        HashMap<Integer, BrandVO> brandMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (BrandDTO brand : salesVOList) {
                int brandId = brand.getBrandId();
                BrandVO brandM = brandMap.get(brandId);
                if (brandM == null) {
                    brandM = new BrandVO();
                }
                // 查询品牌名称
                brandM.setBrandName(brand.getBrandName());
                brandM.setChainId(brand.getChainId());
                brandM.setBrandId(brandId);
                brandM.setYearId(brandOrderSalerBO.getYearId());
                brandM.setQuarterId(brandOrderSalerBO.getQuarterId());
                if (brand.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    brandM.setNetSalesAmount(brandM.getNetSalesAmount() + brand.getNetSalesAmount());
                    brandM.setNetSalesVolume(brandM.getNetSalesVolume() + brand.getNetSalesVolume());
                    brandM.setNetCost((int) (brandM.getNetCost() + brand.getNetCost()));
                    brandM.setProfit(brandM.getProfit() + brand.getNetSalesAmount() - brand.getNetCost());
                } else if (brand.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    brandM.setNetSalesAmount(brandM.getNetSalesAmount() - brand.getNetSalesAmount());
                    brandM.setNetSalesVolume(brandM.getNetSalesVolume() - brand.getNetSalesVolume());
                    brandM.setNetCost((int) (brandM.getNetCost() - brand.getNetCost()));
                    brandM.setProfit(brandM.getProfit() - (brand.getNetSalesAmount() - brand.getNetCost()));
                } else if (brand.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    brandM.setGiftQuantity(brandM.getGiftQuantity() + brand.getNetSalesVolume());
                    brandM.setProfit(brandM.getProfit() - brand.getNetCost());
                }
                brandMap.put(brandId, brandM);
            }
        }
        for (BrandVO brandVO : brandMap.values()) {
            list.add(brandVO);
        }
        return list.stream().sorted(Comparator.comparing(BrandVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<CategoryVO> selectByCategory(BrandOrderSalerBO brandOrderSalerBO) {
        List<CategoryVO> list = new ArrayList<>();
        List<Integer> chainIds = new ArrayList<>();
        List<Integer> chainId = new ArrayList<>();
        if (StringUtils.isNotNull(brandOrderSalerBO.getChainStore())) {
            chainId.add(brandOrderSalerBO.getChainStore());
        } else {
            chainIds = getSalesBo(CommonSalesBO.builder()
                    .userType(brandOrderSalerBO.getUserType())
                    .userId(brandOrderSalerBO.getUserId())
                    .chainStore(brandOrderSalerBO.getChainStore())
                    .startTime(brandOrderSalerBO.getStartTime())
                    .endTime(brandOrderSalerBO.getEndTime())
                    .build()).getChainStore();
        }
        // 查询所有类别信息
        List<CategoryDTO> salesVOList = orderProductMapper.selectCategoryDto(
                brandOrderSalerBO.getYearId(),
                brandOrderSalerBO.getQuarterId(),
                brandOrderSalerBO.getChainStore() == null ? chainIds : chainId,
                brandOrderSalerBO.getHandledBy(),
                brandOrderSalerBO.getStartTime(),
                brandOrderSalerBO.getEndTime());
        HashMap<Integer, CategoryVO> categoryvoMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (CategoryDTO categoryDTO : salesVOList) {
                int categoryId = categoryDTO.getCategoryId();
                CategoryVO categoryvoM = categoryvoMap.get(categoryId);
                if (categoryvoM == null) {
                    categoryvoM = new CategoryVO();
                }
                // 查询品牌名称
                categoryvoM.setCategoryId(categoryId);
                categoryvoM.setCategoryName(categoryMapper.selectCategoryName(categoryId));
                categoryvoM.setYearId(brandOrderSalerBO.getYearId());
                categoryvoM.setQuarterId(brandOrderSalerBO.getQuarterId());
                if (categoryDTO.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    categoryvoM.setNetSalesAmount(categoryvoM.getNetSalesAmount() + categoryDTO.getNetSalesAmount());
                    categoryvoM.setNetSalesVolume(categoryvoM.getNetSalesVolume() + categoryDTO.getNetSalesVolume());
                    categoryvoM.setNetCost((int) (categoryvoM.getNetCost() + categoryDTO.getNetCost()));
                    categoryvoM.setProfit(categoryvoM.getProfit() + categoryDTO.getNetSalesAmount() - categoryDTO.getNetCost());
                } else if (categoryDTO.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    categoryvoM.setNetSalesAmount(categoryvoM.getNetSalesAmount() - categoryDTO.getNetSalesAmount());
                    categoryvoM.setNetSalesVolume(categoryvoM.getNetSalesVolume() - categoryDTO.getNetSalesVolume());
                    categoryvoM.setNetCost((int) (categoryvoM.getNetCost() - categoryDTO.getNetCost()));
                    categoryvoM.setProfit(categoryvoM.getProfit() - (categoryDTO.getNetSalesAmount() - categoryDTO.getNetCost()));
                } else if (categoryDTO.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    categoryvoM.setGiftQuantity(categoryvoM.getGiftQuantity() + categoryDTO.getNetSalesVolume());
                    categoryvoM.setProfit(categoryvoM.getProfit() - categoryDTO.getNetCost());
                }
                categoryvoMap.put(categoryId, categoryvoM);
            }
        }
        for (CategoryVO categoryVO : categoryvoMap.values()) {
            list.add(categoryVO);
        }
        return list.stream().sorted(Comparator.comparing(CategoryVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }


    @Override
    public List<ProductStatisticsVO> selectByProduct(ProductSalerBO productSalerBO) throws IOException {
        List<ProductStatisticsVO> list = new ArrayList<>();
        List<Integer> chainIds = new ArrayList<>();
        List<Integer> chainId = new ArrayList<>();
        if (StringUtils.isNotNull(productSalerBO.getChainStore())) {
            chainId.add(productSalerBO.getChainStore());
        } else {
            chainIds = getSalesBo(CommonSalesBO.builder()
                    .userType(productSalerBO.getUserType())
                    .userId(productSalerBO.getUserId())
                    .chainStore(productSalerBO.getChainStore())
                    .startTime(productSalerBO.getStartTime())
                    .endTime(productSalerBO.getEndTime())
                    .build()).getChainStore();
        }
        // 查询具体商品
        List<CommodityDTO> salesVOList = orderProductMapper.selectCommodityDto(
                productSalerBO.getYearId(),
                productSalerBO.getQuarterId(),
                productSalerBO.getBrandId(),
                productSalerBO.getChainStore() == null ? chainIds : chainId,
                productSalerBO.getHandledBy(),
                productSalerBO.getStartTime(),
                productSalerBO.getEndTime());
        HashMap<Integer, ProductStatisticsVO> productMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (CommodityDTO commodityDTO : salesVOList) {
                System.out.println(commodityDTO.getProductId());
                int productId = commodityDTO.getProductId();
                ProductStatisticsVO productStatisticsVO = productMap.get(productId);
                if (productStatisticsVO == null) {
                    productStatisticsVO = new ProductStatisticsVO();
                }
                String colorName = "";  // 颜色名称
                if (StringUtils.isNotNull(colorMapper.selectColorName(commodityDTO.getColorId()))) {
                    colorName = colorMapper.selectColorName(commodityDTO.getColorId());
                }
                String brandName = "";    // 查询品牌名称
                if (StringUtils.isNotNull(colorMapper.selectBrandName(commodityDTO.getBrandId()))) {
                    brandName = colorMapper.selectBrandName(commodityDTO.getBrandId());
                }
//                productStatisticsVO.setCommodity(commodityDTO.getProductCode() + colorName + " " + brandName); // 商品信息
                productStatisticsVO.setCommodity(commodityDTO.getProductCode() + colorName); // 商品信息
                productStatisticsVO.setChainId(commodityDTO.getChainId());
                productStatisticsVO.setBarcode(commodityDTO.getBarcode()); // 商品条码

                if (commodityDTO.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    productStatisticsVO.setNetSalesAmount(productStatisticsVO.getNetSalesAmount() + commodityDTO.getNetSalesAmount());
                    productStatisticsVO.setNetSalesVolume(productStatisticsVO.getNetSalesVolume() + commodityDTO.getNetSalesVolume());
                    productStatisticsVO.setNetCost((int) (productStatisticsVO.getNetCost() + commodityDTO.getNetCost()));
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() + commodityDTO.getNetSalesAmount() - commodityDTO.getNetCost());
                } else if (commodityDTO.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    productStatisticsVO.setNetSalesAmount(productStatisticsVO.getNetSalesAmount() - commodityDTO.getNetSalesAmount());
                    productStatisticsVO.setNetSalesVolume(productStatisticsVO.getNetSalesVolume() - commodityDTO.getNetSalesVolume());
                    productStatisticsVO.setNetCost((int) (productStatisticsVO.getNetCost() - commodityDTO.getNetCost()));
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() - (commodityDTO.getNetSalesAmount() - commodityDTO.getNetCost()));
                } else if (commodityDTO.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    productStatisticsVO.setGiftQuantity(productStatisticsVO.getGiftQuantity() + commodityDTO.getNetSalesVolume());
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() - commodityDTO.getNetCost());
                }
                productMap.put(productId, productStatisticsVO);
            }
        }

        for (ProductStatisticsVO productStatisticsVO : productMap.values()) {
            productStatisticsVO.setChainId(productStatisticsVO.getChainId());
            productStatisticsVO.setExist(zipImgUtils.picIsExist(productStatisticsVO.getBarcode()));
            list.add(productStatisticsVO);
        }
        return list.stream().sorted(Comparator.comparing(ProductStatisticsVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }

    @Override
    //
    public List<ProductStatisticsVO> selectCategoryDetail(CatetoryDetailBO catetoryDetailBO) throws IOException {
        List<ProductStatisticsVO> list = new ArrayList<>();
        List<Integer> chainIds = new ArrayList<>();
        List<Integer> chainId = new ArrayList<>();
        if (StringUtils.isNotNull(catetoryDetailBO.getChainStore())) {
            chainId.add(catetoryDetailBO.getChainStore());
        } else {
            chainIds = getSalesBo(CommonSalesBO.builder()
                    .userType(catetoryDetailBO.getUserType())
                    .userId(catetoryDetailBO.getUserId())
                    .chainStore(catetoryDetailBO.getChainStore())
                    .startTime(catetoryDetailBO.getStartTime())
                    .endTime(catetoryDetailBO.getEndTime())
                    .build()).getChainStore();
        }
        // 查询具体商品
        List<CategoryDetailDTO> salesVOList = orderProductMapper.selectCategoryDetailDTO(
                catetoryDetailBO.getYearId(),
                catetoryDetailBO.getQuarterId(),
                catetoryDetailBO.getCategoryId(),
                catetoryDetailBO.getChainStore() == null ? chainIds : chainId,
                catetoryDetailBO.getHandledBy(),
                catetoryDetailBO.getStartTime(),
                catetoryDetailBO.getEndTime()
        );
        HashMap<Integer, ProductStatisticsVO> productMap = new HashMap<>();
        if (StringUtils.isNotEmpty(salesVOList)) {
            for (CategoryDetailDTO categoryDetailDTO : salesVOList) {
                int categoryId = categoryDetailDTO.getProductId();
                ProductStatisticsVO productStatisticsVO = productMap.get(categoryId);
                if (productStatisticsVO == null) {
                    productStatisticsVO = new ProductStatisticsVO();
                }
                // 查询品牌名称
                String colorName = "";
                if (StringUtils.isNotNull(colorMapper.selectColorName(categoryDetailDTO.getColorId()))) {
                    colorName = colorMapper.selectColorName(categoryDetailDTO.getColorId());
                }
                String brandName = "";    // 查询品牌名称
                if (StringUtils.isNotNull(colorMapper.selectBrandName(categoryDetailDTO.getBrandId()))) {
                    brandName = colorMapper.selectBrandName(categoryDetailDTO.getBrandId());
                }
                productStatisticsVO.setChainId(categoryDetailDTO.getChainId());
                productStatisticsVO.setCommodity(categoryDetailDTO.getProductCode() + colorName + " " + brandName);
                productStatisticsVO.setBarcode(categoryDetailDTO.getBarcode()); // 商品条码
                if (categoryDetailDTO.getType() == ProductSaleStatus.SALE_GOODS.getStatus()) {
                    productStatisticsVO.setNetSalesAmount(productStatisticsVO.getNetSalesAmount() + categoryDetailDTO.getNetSalesAmount());
                    productStatisticsVO.setNetSalesVolume(productStatisticsVO.getNetSalesVolume() + categoryDetailDTO.getNetSalesVolume());
                    productStatisticsVO.setNetCost((int) (productStatisticsVO.getNetCost() + categoryDetailDTO.getNetCost()));
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() + categoryDetailDTO.getNetSalesAmount() - categoryDetailDTO.getNetCost());
                } else if (categoryDetailDTO.getType() == ProductSaleStatus.RETURNED_GOODS.getStatus()) {
                    productStatisticsVO.setNetSalesAmount(productStatisticsVO.getNetSalesAmount() - categoryDetailDTO.getNetSalesAmount());
                    productStatisticsVO.setNetSalesVolume(productStatisticsVO.getNetSalesVolume() - categoryDetailDTO.getNetSalesVolume());
                    productStatisticsVO.setNetCost((int) (productStatisticsVO.getNetCost() - categoryDetailDTO.getNetCost()));
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() - (productStatisticsVO.getNetSalesAmount() - categoryDetailDTO.getNetCost()));
                } else if (categoryDetailDTO.getType() == ProductSaleStatus.GIFTS_GOODS.getStatus()) {
                    productStatisticsVO.setGiftQuantity(productStatisticsVO.getGiftQuantity() + categoryDetailDTO.getNetSalesVolume());
                    productStatisticsVO.setProfit(productStatisticsVO.getProfit() - categoryDetailDTO.getNetCost());
                }
                productMap.put(categoryId, productStatisticsVO);
            }
        }

        for (ProductStatisticsVO productStatisticsVO : productMap.values()) {
            productStatisticsVO.setExist(zipImgUtils.picIsExist(productStatisticsVO.getBarcode()));
            list.add(productStatisticsVO);
        }
        return list.stream().sorted(Comparator.comparing(ProductStatisticsVO::getNetSalesVolume).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<GoodsDetailsVO> selectGoogSDetails(GoodsDetailsBO goodsDetailsBO) {
        List<GoodsDetailsVO> detailsVOS = new ArrayList<>();
        if (StringUtils.isEmpty(goodsDetailsBO.getStoreId())) { // 总部查询所有cliendId
            List<Integer> clientIds = new ArrayList<>();
            if (goodsDetailsBO.getUserType() == LoginUserType.HEADQUARTERS.getNumber()) { //总部用户
                clientIds = chainStoreMapper.SelectClientIds();
            } else {  // 连锁店用户
                ChainUserInfor chainUserInfor = chainUserInforMapper.selectByUserId(goodsDetailsBO.getUserId()); // 查询连锁店用户信息
                // 直营连锁店
                // todo (原判断直营连锁店：位置6 ，共6处）
                //非直营连锁店
                if (chainUserInfor.getRoleType() == ChainRoleType.CHAIN_STORE_OPERATOR.getRoleType()) { // 连锁店经营者
                    List<ChainStoreVO> list = chainStoreService.selectStoreId(goodsDetailsBO.getUserId(), goodsDetailsBO.getUserType());
                    List<Integer> chainIds = new ArrayList<>();
                    list.stream().forEach(chainStoreVO -> {
                        chainIds.add(chainStoreVO.getValue());
                    });
                    clientIds = chainStoreMapper.selectOperatorClientIds(chainIds); // 经营者所有店铺
                } else { // 店长，店员
                    Integer clientId = chainStoreMapper.selectClientId(String.valueOf(chainUserInfor.getChainId()));
                    clientIds.add(clientId);
                }

            }
            List<GoodsDetailsDTO> goods = chainInOutStockMapper.selectAllDetails(clientIds, goodsDetailsBO.getBarcode());
            goods.stream().forEach(goodsDetailsDTO -> {
                detailsVOS.add(commonDetails(goodsDetailsDTO));
            });
            return detailsVOS;
        } else { // 单店铺查询
            Integer clientId = chainStoreMapper.selectClientId(goodsDetailsBO.getStoreId()); //  查询clientId
            if (StringUtils.isNotNull(clientId)) {
                List<GoodsDetailsDTO> list = chainInOutStockMapper.selectGoodsDetails(clientId, goodsDetailsBO.getBarcode());
                list.stream().forEach(goodsDetailsDTO -> {
                    detailsVOS.add(commonDetails(goodsDetailsDTO));
                });
            }
        }
        return detailsVOS;
    }

    public GoodsDetailsVO commonDetails(GoodsDetailsDTO goodsDetailsDTO) {
        int i = -1;
        Matcher matcher = Pattern.compile("[0-9]").matcher(goodsDetailsDTO.getOrderID());//
        if (matcher.find()) {
            i = matcher.start();  //下标位置
        }
        String chainStroreName = chainStoreMapper.selectByClientId(goodsDetailsDTO.getClientId());
        return GoodsDetailsVO.builder()
                .code(goodsDetailsDTO.getOrderID().substring(0, i))
                .createTime(goodsDetailsDTO.getCreateTime())
                .number(goodsDetailsDTO.getQuantiry())
                .chainName(chainStroreName)
                .documentCode(goodsDetailsDTO.getOrderID().substring(i, goodsDetailsDTO.getOrderID().length()))
                .describe(DocumentType.getDocumentMsg(goodsDetailsDTO.getOrderID().substring(0, i)))
                .build();
    }


}
